package com.acme.javaschool.intense.sems.sem3logging;

import java.io.IOException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public abstract class Appender {
    protected final String IO_FAIL_MESSAGE = "Appender: IO failed.";

    public int bufferSize;
    BlockingQueue<Object[]> messages;
    public final AppenderType type;


    protected Appender(int bufferSize, AppenderType type) {
        messages = new ArrayBlockingQueue<>(bufferSize);
        this.bufferSize = bufferSize;
        this.type = type;

        (new Thread() {
            @Override
            public void run() {
                while (true) {
                    try {
                        write(messages.take());
                    } catch (IOException e) {
                        try {
                            write(IO_FAIL_MESSAGE);
                        } catch (IOException e1) { }
                    } catch (InterruptedException e) { /* ??? */ }
                }
            }
        }).start();
    }

    protected abstract void write(Object... message) throws IOException;

    public void submit(Object... message) {
        if (message != null) {
            messages.offer(message);
        }
    }

}
